import React, { Component, Fragment } from 'react'
import { inject, observer } from 'mobx-react/index'
import { Breadcrumb } from 'antd'
import Cookies from 'js-cookie'
import { Link } from 'react-router-dom'
import pathToRegexp from 'path-to-regexp'

@inject('DataApprovalModel', 'BreadCrumb', 'SocketModel', 'RegionId')
@observer
export default class BreadCrumb extends Component {
  get breadcrumbNameMap() {
    const orgName = Cookies.get('org')
    const leagueName = Cookies.get('league')
    return {
      '/dashboard': '',
      '/dashboard/event': '事件中心',
      '/dashboard/user': '用户中心',
      '/dashboard/setting': '系统设置',
      '/dashboard/fabric': '联盟链',
      '/dashboard/cross-chain': '跨链',
      '/dashboard/log': '审计日志',
      '/dashboard/cross-chain/blockList': '块列表',
      '/dashboard/cross-chain/txList': '交易列表',
      '/dashboard/cross-chain/txInfo': '交易详情',
      '/dashboard/cross-chain/communicationChain/new': '创建通讯链',
      '/dashboard/cross-chain/communicationChain/info/:id': '通讯链详情',
      '/dashboard/cross-chain/contracts': '通讯合约列表',
      '/dashboard/cross-chain/applications': '跨链申请列表',
      '/dashboard/fabric/createOrganization': '构建组织',
      '/dashboard/fabric/organizationInfo/:id': orgName,
      '/dashboard/fabric/organizationInfo/:id/createPeer': '新增节点',
      '/dashboard/fabric/invite': '加入联盟',
      '/dashboard/fabric/:id/:name/apply': '申请加入组织',
      '/dashboard/fabric/createLeague': '构建联盟',
      '/dashboard/fabric/leagueInfo/:id/:name': leagueName,
      '/dashboard/fabric/leagueInfo/:id/:name/allBlock/:bId': '全部区块',
      '/dashboard/fabric/leagueInfo/:id/:name/blockDetail/:cId/:bId': '区块详情',
      '/dashboard/fabric/leagueInfo/:id/:name/allTransactions/:bId': '全部交易',
      '/dashboard/fabric/leagueInfo/:id/:name/transactionsDetail/:cId/:bId': '交易详情',
      '/dashboard/fabric/leagueInfo/:id/:name/createChannel': '创建通道',
      '/dashboard/fabric/leagueInfo/:id/:name/joinChannel/:channelId/:channelName/:type': '添加组织',
      '/dashboard/fabric/leagueInfo/:id/:name/channelOrg/:channelId/:channelName': '组织管理',
      '/dashboard/fabric/leagueInfo/:id/:name/channelOrg/:channelId/:channelName/addNode/:peerId/:peerName': '添加节点',
      '/dashboard/fabric/leagueInfo/:id/:name/policyManagement': '策略管理',
      '/dashboard/applicationService': '应用服务',
      '/dashboard/applicationService/serviceDetails': '服务详情',
    }
  }

  goBack = () => {
    this.props.history.goBack()
  }

  conversionFromLocation = (routerLocation) => {
    const { state } = this.props.location
    let pathSnippets = urlToList(routerLocation.pathname)
    pathSnippets = pathSnippets.filter(url => {
      return typeof (getBreadcrumb(this.breadcrumbNameMap, url, this.props.location)) !== 'object'
    })
    return pathSnippets.map((url, index) => {
      const currentBreadcrumb = getBreadcrumb(this.breadcrumbNameMap, url, this.props.location)
      const isLinkable = index !== pathSnippets.length - 1 && currentBreadcrumb
      return currentBreadcrumb && typeof (currentBreadcrumb) !== 'object' && url !== '/dashboard' && (
        <Breadcrumb.Item key={url}>
          {
            isLinkable
              ? <Link className="link-click" to={{ pathname: url, state: state ? { ...state } : {}}}>
                {currentBreadcrumb}
              </Link>
              : <span className="link-no-click">{currentBreadcrumb}</span>
          }
        </Breadcrumb.Item>
      )
    })
  };

  getRouteTitle = (pathArr) => {
    if (!pathArr.length) return false
    const { menuList } = this.props
    return <div className="route-title">
      <span className="title" style={{ margin: 0 }}>{(menuList.filter(item => item.path === pathArr[0].key)[0] || {}).name}</span>
    </div>
  }

  render() {
    const { BreadCrumb: { url_apply, search_apply }} = this.props
    const pathArr = this.conversionFromLocation(this.props.location).filter(v => v)
    return <Fragment>
      {
        pathArr.length <= 1 ? this.getRouteTitle(pathArr)
          : <div className="breadcrumb">
            <div className="breadcrumb-back" onClick={this.goBack} />
            {
              search_apply && url_apply
                ? <Breadcrumb>
                  <Breadcrumb.Item key="apply_url">
                    <Link className="link-click" to={{ pathname: url_apply }}>
                      {search_apply}
                    </Link>
                  </Breadcrumb.Item>
                  <Breadcrumb.Item key="apply_tit">
                    <span>申请添加组织</span>
                  </Breadcrumb.Item>
                </Breadcrumb>
                : <Breadcrumb>
                  {pathArr}
                </Breadcrumb>
            }
          </div>
      }
    </Fragment>
  }
}

function urlToList(url) {
  const urllist = url.split('/').filter(i => i)
  return urllist.map((urlItem, index) => {
    return `/${urllist.slice(0, index + 1).join('/')}`
  })
}

function getBreadcrumb(breadcrumbNameMap, url, props) {
  let breadcrumb = breadcrumbNameMap[url]
  if (!breadcrumb) {
    Object.keys(breadcrumbNameMap).forEach(item => {
      if (pathToRegexp(item).test(url)) {
        breadcrumb = breadcrumbNameMap[item]
      }
    })
  }
  return breadcrumb || {}
}

